package com.trkj.service;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.trkj.dao.jpa.IEquipStroageSaveDao;
import com.trkj.dao.jpa.IEreturnDetailDao;
import com.trkj.dao.jpa.IStorageReturnDao;
import com.trkj.dao.mybatis.IStorageReturnMapper;
import com.trkj.pojos.BusPeople;
import com.trkj.pojos.EquipReturngood;
import com.trkj.pojos.EquipStroageSave;
import com.trkj.pojos.EreturnDetail;

@Service
@Transactional
public class StorageReturnService {
	@Autowired
	private IStorageReturnMapper returnMapper;
	@Autowired
	private IStorageReturnDao returnDao;
	@Autowired
	private IEreturnDetailDao returnDetailDao;
	@Autowired
	private IEquipStroageSaveDao equipStroageSaveDao;
	
	
	public Map<String, Object> findEquipReturngood(int page, int rows) {
		Page<EquipReturngood> p = PageHelper.startPage(page, rows, true);
		List<EquipReturngood> list = returnMapper.findEquipReturngood();
		Map<String,Object> map = new HashMap<>();
		map.put("total", p.getTotal());
		map.put("rows", list);
		return map;	
	}

	public String createEquipReturnId() {
		String equipReturnId = "";
		//将当前日期格式化为纯数字
		SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
		String str = sdf.format(new Date()).substring(2, 8);
		
		String LikeID = "%" + str + "%";
		List<String> list = returnDao.queryEquipReturnId(LikeID);

		if(list.isEmpty()){
			equipReturnId = "RG" + str +"0001";
		}else{
			List<Integer> lists = new ArrayList<>();
			for(int i=0;i<list.size();i++){
				lists.add(Integer.valueOf(list.get(i).toString().substring(8, 12)));
			}
			//Collections.max取最大值再加1，拼接住院号
			 int next = Collections.max(lists).intValue()+1;
			 String nextID = String.format("%04d", next);
			 equipReturnId = "RG" + str + nextID;
		}
		return equipReturnId;
	}
	/**
	 * 添加退货订单
	 * @param returnGood
	 * @param asList
	 * @param list 
	 * @return
	 */
	public boolean EosReturn(EquipReturngood returnGood, List<EreturnDetail> asList, Long[] list) {
		try {
			returnDao.save(returnGood);	
			String ereturnId = returnGood.getEreturnId();
			//绑定关系
			if(asList!=null){
				for (EreturnDetail ereturnDetail : asList) {
					ereturnDetail.setEreturnId(ereturnId);
				}
			}
			if(list!=null){
				for (Long is : list) {
					EquipStroageSave findOne = equipStroageSaveDao.findOne(is);
					equipStroageSaveDao.delete(findOne);
				}
			}
			returnDetailDao.save(asList);	
			return true;
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}
	}
}
